//
//  WKWebViewController.m
//  WKWebViewMessageHandlerDemo
//
//  Created by reborn on 16/9/12.
//  Copyright © 2016年 reborn. All rights reserved.
//

#import "WKWebViewController.h"
#import <WebKit/WebKit.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>
#import "Weixin.h"

#import "WXApi.h"

#import "LoginVC.h"

@interface WKWebViewController ()<WKUIDelegate,WKScriptMessageHandler>

@property(nonatomic, strong)WKWebView *webView;
@end

@implementation WKWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    
    self.title = @"WKWebViewMessageHandler";
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self initWKWebView];
}

- (void)initWKWebView
{

    //创建并配置WKWebView的相关参数
    //1.WKWebViewConfiguration:是WKWebView初始化时的配置类，里面存放着初始化WK的一系列属性；
    //2.WKUserContentController:为JS提供了一个发送消息的通道并且可以向页面注入JS的类，WKUserContentController对象可以添加多个scriptMessageHandler；
    //3.addScriptMessageHandler:name:有两个参数，第一个参数是userContentController的代理对象，第二个参数是JS里发送postMessage的对象。添加一个脚本消息的处理器,同时需要在JS中添加，window.webkit.messageHandlers.<name>.postMessage(<messageBody>)才能起作用。
    
    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
    WKUserContentController *userContentController = [[WKUserContentController alloc] init];
    
    [userContentController addScriptMessageHandler:self name:@"shareWeixinInfo"];
    [userContentController addScriptMessageHandler:self name:@"weixinPay"];
    [userContentController addScriptMessageHandler:self name:@"logout"];
    
    configuration.userContentController = userContentController;
    
    
    WKPreferences *preferences = [WKPreferences new];
    preferences.javaScriptCanOpenWindowsAutomatically = YES;
    preferences.minimumFontSize = 10.0;
    configuration.preferences = preferences;
    
    self.webView.scrollView.scrollEnabled = NO;
    self.webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:configuration];
    
    [self.webView setBackgroundColor:[UIColor blackColor]];
    
    
//    //loadFileURL方法通常用于加载服务器的HTML页面或者JS，而loadHTMLString通常用于加载本地HTML或者JS
//    NSString *htmlPath = [[NSBundle mainBundle] pathForResource:@"WKWebViewMessageHandler" ofType:@"html"];
//    NSString *fileURL = [NSString stringWithContentsOfFile:htmlPath encoding:NSUTF8StringEncoding error:nil];
//    NSURL *baseURL = [NSURL fileURLWithPath:htmlPath];
//    [self.webView loadHTMLString:fileURL baseURL:baseURL];
    
//    
    NSString *url = [[NSString stringWithFormat:@"http://dog.ie1e.com:8081/index.html?uid=%@",[stan objectForKey:userID]] stringByAppendingString:@"&plat=2"];
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
    NSLog(@"%s  %d  %@",__func__,__LINE__,url);
    
    
    self.webView.UIDelegate = self;
    
    [self.view addSubview:self.webView];
}

#pragma mark - WKUIDelegate
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
{

}

#pragma mark -- WKScriptMessageHandler
/**
 *  JS 调用 OC 时 webview 会调用此方法
 *
 *  @param userContentController  webview中配置的userContentController 信息
 *  @param message                JS执行传递的消息
 */

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    //JS调用OC方法
    
    //message.boby就是JS里传过来的参数
    NSLog(@"body:%@",message.body);
    
    if ([message.name isEqualToString:@"shareWeixinInfo"]) {
        
        if (([WXApi isWXAppInstalled])) {
            [self ShareWithInformation:message.body];
        } else {
            [self alertWithTitle:@"友情提示" withMsg:@"未安装微信"];
        }

    } else if ([message.name isEqualToString:@"weixinPay"]) {
        if (([WXApi isWXAppInstalled])) {
            NSLog(@"%s  %d  %zd",__func__,__LINE__,[WXApi isWXAppInstalled]);
            [self wxpay:message.body];
        } else {
            [self alertWithTitle:@"友情提示" withMsg:@"未安装微信"];
        }
    } else if ([message.name isEqualToString:@"logout"]) {
        [self logout];
    }
}

- (void)alertWithTitle:(NSString *)title withMsg:(NSString *)msg {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:msg preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    
    [self presentViewController:alert animated:YES completion:nil];

}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    NSLog(@"%s  %d  %@",__func__,__LINE__,decisionHandler);
}


#pragma mark - Method
- (void)ShareWithInformation:(NSDictionary *)dic {
    [Weixin weixinShareWithDescription:dic[@"content"]];
}

- (void)wxpay:(NSDictionary *)dic
{
    NSLog(@"%s  %d  ",__func__,__LINE__);
    NSString *eqipName = dic[@"eName"];
    NSString *eqipPrice = dic[@"ePrice"];
    
    [stan setObject:eqipName forKey:eName];
    [stan setObject:eqipPrice forKey:ePrice];
    [stan synchronize];
    
    [Weixin weixinPay];
}

- (void)logout {
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end
